<template>
  <view>
    <form @submit="saveUser">
      <view class="line">
        <view class="left">头像</view>
        <view class="right">
          <button open-type="chooseAvatar" class="btnAvatar" @chooseavatar="chooseavatar">
            <image class="avatar" :src="formData.avatar"></image>
          </button>
          <view class="arrow"></view>
        </view>
      </view>
      <view class="line">
        <view class="left">昵称</view>
        <view class="right">
          <input type="nickname" name="nickname" :value="formData.nickname" />
          <view class="arrow"></view>
        </view>
      </view>
      <view class="line">
        <view class="left">真实姓名</view>
        <view class="right">
          <input type="text" name="name" :value="formData.name" />
          <view class="arrow"></view>
        </view>
      </view>
      <view class="line">
        <view class="left">手机号码</view>
        <view class="right">
          <input type="text" name="mobile" :value="formData.mobile" />
          <view class="arrow"></view>
        </view>
      </view>
      <view class="btnLogin">
        <button type="primary" form-type="submit">立即保存</button>
      </view>
    </form>
  </view>
</template>


<script>
  export default {
    data() {
      return {
        formData: {}
      };
    },
    onLoad() {
      this.initData()
    },
    methods: {
      // 回显数据
      async initData() {
        let res = await uni.$http.get('/user/profile')
        this.formData = res
      },
      // 获取头像
      chooseavatar(event) {
        // 关于此问题：https://developers.weixin.qq.com/community/develop/doc/0006a858c78b382120feb83f056c00?jumpto=comment&commentid=000caa0f3f08b83128fe5b3935b0
        this.formData.avatar = event.detail.avatarUrl // 视图临时更新
      },
      // 点击提交后就是提交表单
      async saveUser(event) {
        let res = await uni.$http.post('/user/update', {
          ...event.detail.value,
          avatar: this.formData.avatar
        })
        // 改变下userInfo
        this.$store.commit('user/setUserInfo', res)
        // 提示成功
        uni.showToast({
          icon: 'none',
          title: '更新成功'
        })
      }
    }
  }
</script>

<style lang="scss">
  .line {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    line-height: 88rpx;
    padding: 0 30rpx;
    align-items: center;

    .right {
      height: 80rpx;
      display: flex;
      align-items: center;
    }

    .arrow {
      border-top: 1px solid #aaa;
      border-right: 1px solid #aaa;
      width: 20rpx;
      height: 20rpx;
      transform: rotateZ(45deg);
    }

    input {
      text-align: right;
      width: 240rpx;
    }
  }

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
  }

  .btnAvatar {
    background-color: #fff;
    width: 100%;
    display: block;
    padding: 0;
    height: 80rpx;
    border: none;
    border-radius: 0;
  }

  .btnLogin {
    margin: 40rpx;
  }
</style>
